package com.vayne.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;

/**
 * {@link java.util.concurrent.atomic.LongAdder}
 * @author xuerui.zhang
 * @since 2020/4/26 下午2:32
 */
public class LongAdderDemo {

    public static void main(String[] args) {
        final LongAdder adder = new LongAdder();
        ExecutorService threadPool = Executors.newFixedThreadPool(20);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            threadPool.submit(new Task(adder));
        }
        threadPool.shutdown();
        while (!threadPool.isTerminated()) {

        }
        long end = System.currentTimeMillis();
        System.out.println(adder.sum());
        System.out.println(end - start);
    }

    private static class Task implements Runnable {

        private LongAdder adder;

        public Task(LongAdder adder) {
            this.adder = adder;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                adder.increment();
            }
        }
    }
}
